<script lang="ts">
//使用<keep-alive></keep-alive>缓存路由必须显式的声明name
export default {
	name: 'goodsinfo',
};
</script>

<script setup lang="ts">
import { query_goodsinfo, query_goodsinfotable, inssert_goodsinfotable, update_goodsinfotable, delete_goodsinfotable } from '../../request/api';
import { ElMessage } from 'element-plus';
import { ref, reactive, onMounted, nextTick } from 'vue';

import { Plus, Refresh, RefreshRight, Setting, EditPen, Delete } from '@element-plus/icons-vue';
import type { ElForm } from 'element-plus';
import type { ElTable } from 'element-plus';

import { useMainStore } from '../../store';
import { storeToRefs } from 'pinia';

//从store里取出菜单数据
const mainStore = useMainStore();
//loding
const loading = ref(false);
//switch的开关
// const loadingswitch = ref(false);

//模态开关
const dialogVisible = ref(false);
//表单框的种类0是新增1是修改
const dialogtype = ref(0);
//表单开关
const formfalg = ref();

//当前列的id名称和id值
const id = reactive({
	name: '',
	value: 0,
});

type FormInstance = InstanceType<typeof ElForm>;
const formRef = ref<FormInstance>();

//设置一进入页面就点击第一页
const goodsinfotableref = ref<InstanceType<typeof ElTable>>();

//监听已
onMounted(() => {
	//设置一进入就默认第一项
	goodsinfotableref.value!.setCurrentRow(goodsinfoname[0]);
});
//点击添加按钮
const tianjia = () => {
	dialogtype.value = 0;
	dialogVisible.value = true;
	// console.log(dialogVisible.value)
};

//商品信息分类的表格数据
var goodsinfoname = [];
const search = ref('');
//商品信息明细表格
var goodsinfotable = ref([]);
//表头
var goodinfoheader = ref([]);
//当前进入的主表
const currenttable = ref('');

//分页
const total = ref(); //总条数
const currentPage = ref(1); //当前页数
const pageSize = ref(10); //每页显示条目个数

//请求商品信息大类名称
const { data } = await query_goodsinfo(1);
if (data.code == 200) {
	goodsinfoname = data.data;
} else {
	ElMessage.error(data.msg);
}
//点击商品信息表格的方法
const handchangegoodsinfo = async (val) => {
	loading.value = true;
	const { data } = await query_goodsinfotable(val.table, currentPage.value, pageSize.value);
	loading.value = false;

	currenttable.value = val.table;
	if (data.code == 200) {
		goodinfoheader.value = data.header;
		goodsinfotable.value = data.data.data;

		total.value = data.data.total; //总条数

		formfalg.value = val.table; //新增表单页的显示

		console.log(goodinfoheader.value);
	} else {
		ElMessage.error(data.msg);
	}

	console.log(data.data.data);
};

//点击开关按钮
//coumname为当前列的字段名,idname为id的名字,val为值
const switchcilik = async (val, coumname, row) => {
	// console.log(val);
	// console.log(goodsinfotable.value);
	let idname = coumname.substr(0, coumname.indexOf('_')) + '_id';
	//要更新的列的id名称和值
	let id = {
		name: idname,
		value: row[idname],
	};
	//要更新的键值对
	let updatedata = {};
	updatedata[coumname] = val;
	//更新商品信息
	const { data } = await update_goodsinfotable(id, currenttable.value, updatedata);
	if (data.code == 200) {
		ElMessage.success('更新成功');
	} else {
		// loadingswitch.value = true;

		ElMessage.error(data.msg);
		RefreshTbale(formfalg.value);
		// console.log(val);
	}
	// console.log(updatedata);
};

//如果更新失败阻止开关切换
const switchbefore = () => {
	// if (loadingswitch.value == true) {
	//   loadingswitch.value = false;
	//   return false;
	// } else {
	//   console.log(loadingswitch.value);
	//   return true;
	// }
	return true;
};

//点击修改按钮
const updateclick = (row) => {
	dialogtype.value = 1;
	dialogVisible.value = true;
	//表单绑定的数据项
	// let formname = formfalg.value.substr(4) + "form";
	let formname = formfalg.value.substr(formfalg.value.indexOf('_') + 1) + 'form';
	//存储id的字段名和id的值
	let idname = formfalg.value.substr(formfalg.value.indexOf('_') + 1) + '_id';
	id.name = idname;
	id.value = row[idname];
	// console.log(id);

	//clearform();
	nextTick(() => {
		Object.keys(eval(formname)).map((key) => {
			console.log(key);
			Object.keys(row).map((key2) => {
				if (key == key2) {
					eval(formname)[key] = row[key2];
				}
			});
		});
	});

	console.log(formfalg.value);
	console.log(row);
	console.log(eval(formname));
};
//点击删除按钮
const delclick = async (row) => {
	//id字段
	let idname = formfalg.value.substr(formfalg.value.indexOf('_') + 1) + '_id';
	const { data } = await delete_goodsinfotable(row[idname], currenttable.value);
	if (data.code == 200) {
		ElMessage.success('删除成功');

		RefreshTbale(formfalg.value);
	} else {
		ElMessage.error(data.msg);
	}
};

//商品种类表单
const GoodsCategoryform = reactive({
	GoodsCategory_name: '',
	// GoodsCategory_weight: 0,
	// GoodsCategory_pieces: 0,
	GoodsCategory_weightunit: '',
});
//商品名称表单
const GoodsNameform = reactive({
	GoodsName_name: '',
});
//品牌表单
const GoodsBrandform = reactive({
	GoodsBrand_name: '',
	GoodsBrand_prefix: '',
	GoodsBrand_remark: '',
});
//成色表单
const GoodsGradeform = reactive({
	GoodsGrade_name: '',
	GoodsGrade_remark: '',
});
//系列表单
const GoodsSeriesform = reactive({
	GoodsSeries_name: '',
	GoodsSeries_remark: '',
});

//表单规则
const rules = reactive({
	//必填项
	GoodsCategory_name: [
		{
			required: true,
			message: '商品种类不能为空',
			trigger: 'blur',
		},
		{
			min: 1,
			max: 11,
			message: '请输入1到10个字符',
			trigger: 'blur',
		},
	],
	GoodsCategory_weightunit: [
		{
			required: true,
			message: '重量单位不能为空',
			trigger: 'blur',
		},
	],
	GoodsName_name: [
		{
			required: true,
			message: '商品名称不能为空',
			trigger: 'blur',
		},
		{
			min: 1,
			max: 11,
			message: '请输入1到10个字符',
			trigger: 'blur',
		},
	],
	GoodsBrand_name: [
		{
			required: true,
			message: '品牌名称不能为空',
			trigger: 'blur',
		},
		{
			min: 1,
			max: 11,
			message: '请输入1到10个字符',
			trigger: 'blur',
		},
	],
	GoodsGrade_name: [
		{
			required: true,
			message: '成色名称不能为空',
			trigger: 'blur',
		},
		{
			min: 1,
			max: 11,
			message: '请输入1到10个字符',
			trigger: 'blur',
		},
	],
	GoodsSeries_name: [
		{
			required: true,
			message: '系列名称不能为空',
			trigger: 'blur',
		},
		{
			min: 1,
			max: 11,
			message: '请输入1到10个字符',
			trigger: 'blur',
		},
	],
});

//监听current-page事件
const handleCurrentChange = async (newpage) => {
	const { data } = await query_goodsinfotable(currenttable.value, newpage, pageSize.value);
	if (data.code == 200) {
		goodsinfotable.value = data.data.data;
	} else {
		ElMessage.error(data.msg);
	}
};
//监听page-size每页条数
const handleSizeChange = async (pagesize) => {
	const { data } = await query_goodsinfotable(currenttable.value, currentPage.value, pagesize);
	if (data.code == 200) {
		goodsinfotable.value = data.data.data;
		console.log(data.data.data);
	} else {
		ElMessage.error(data.msg);
	}
};

//关闭模态框之前清空表单数据
const beforeclosedialog = (done) => {
	//清空表单数据
	formRef.value!.resetFields();
	return done(false);
};
//点击模态框取消按钮
const cancel = (formEl: FormInstance | undefined) => {
	//clearform();
	formRef.value!.resetFields();
	dialogVisible.value = false;
};
//点击模态框中的确认按钮
const dianlogclick = (formfalg, formEl: FormInstance | undefined) => {
	if (!formEl) return;

	formEl.validate(async (valid) => {
		if (valid) {
			//let formname = formfalg.substr(4) + "form";
			let formname = formfalg.substr(formfalg.indexOf('_') + 1) + 'form';
			let foremdata = eval(formname);
			//如果dialogtype是0就是新增
			if (dialogtype.value == 0) {
				//插入新数据
				const { data } = await inssert_goodsinfotable(formfalg, foremdata);
				if (data.code == 200) {
					ElMessage.success('新增成功');

					formEl.resetFields();
					dialogVisible.value = false;
					//重新请求数据
					RefreshTbale(formfalg);
				} else {
					ElMessage.error(data.msg);
					formEl.resetFields();
					dialogVisible.value = false;
				}
				//如果dialogtype是1就是修改
			} else if (dialogtype.value == 1) {
				console.log(foremdata);
				const { data } = await update_goodsinfotable(id, currenttable.value, foremdata);
				if (data.code == 200) {
					dialogVisible.value = false;
					formEl.resetFields();
					ElMessage.success('修改成功');

					//重新请求数据
					RefreshTbale(formfalg);
				} else {
					ElMessage.error(data.msg);
				}
			}
		} else {
			console.log('验证失败');
			return false;
		}
	});
};
//点击刷新按钮
const refreshclick = () => {
	RefreshTbale(formfalg.value);
	ElMessage.success('刷新成功');
};

//点击列设置按钮
const coumset = () => {
	console.log(goodinfoheader.value);
};

//刷新表格数据
const RefreshTbale = async (formfalg) => {
	const { data } = await query_goodsinfotable(formfalg, currentPage.value, pageSize.value);
	// loading.value = false;
	if (data.code == 200) {
		goodsinfotable.value = data.data.data;
		total.value = data.data.total;
	} else {
		ElMessage.error(data.msg);
	}
};
</script>

<template>
	<div class="el-card_body">
		<el-row :gutter="20">
			<el-col :span="24" :lg="6">
				<el-table ref="goodsinfotableref" class="left_table" :data="goodsinfoname" border highlight-current-row style="width: 100%" :header-cell-style="{ background: '#f6f8f9', color: '#000000' }" height="calc(100vh - 261px)" max-height="calc(100vh - 261px)" @current-change="handchangegoodsinfo">
					<el-table-column align="center" type="index" width="50" />
					<el-table-column prop="name" label="商品信息" />
				</el-table>
			</el-col>
			<el-col :span="24" :lg="18">
				<el-table v-loading="loading" :data="goodsinfotable" border style="width: 100%" height="calc(100vh - 261px)" max-height="calc(100vh - 261px)" :header-cell-style="{ background: '#f6f8f9', color: '#000000' }">
					<el-table-column label="Address Info">
						<template #header>
							<div class="ele-table-tool ele-table-tool-default">
								<el-button type="primary" :icon="Plus" @click="tianjia">添加</el-button>
								<div class="ele-tool">
									<el-tooltip effect="dark" content="刷新" placement="top">
										<el-button size="small" :icon="Refresh" @click="refreshclick"></el-button>
									</el-tooltip>

									<el-tooltip effect="dark" content="列设置" placement="top">
										<el-button size="small" :icon="Setting" @click="coumset"></el-button>
									</el-tooltip>
								</div>
							</div>
						</template>
						<el-table-column align="center" type="index" width="50" />
						<template v-for="(item, index) in goodinfoheader" :key="index">
							<el-table-column resizable :prop="item.prop" :label="item.lable" align="center" v-if="!item.switch" min-width="100" />
							<el-table-column :prop="item.prop" :label="item.lable" v-if="item.switch" align="center" width="80">
								<template #default="scope">
									<el-switch v-model="scope.row[item.prop]" :active-value="1" :inactive-value="0" @change="switchcilik(scope.row[item.prop], item.prop, scope.row)" :before-change="switchbefore" />
								</template>
							</el-table-column>
						</template>
						<el-table-column fixed="right" align="center" label="操作" width="140">
							<template #default="scope">
								<el-button type="text" :icon="EditPen" @click="updateclick(scope.row)">修改</el-button>
								<el-popconfirm @confirm="delclick(scope.row)" title="是否确认删除?">
									<template #reference>
										<el-button class="operate" type="text" :icon="Delete">删除</el-button>
									</template>
								</el-popconfirm>
							</template>
						</el-table-column>
					</el-table-column>
				</el-table>
				<div class="ele-pagination">
					<el-pagination v-model:currentPage="currentPage" background :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="total" @update:current-page="handleCurrentChange" @update:page-size="handleSizeChange"></el-pagination>
				</div>
			</el-col>
		</el-row>
	</div>
	<!-- 表单的弹出框 -->
	<el-dialog :before-close="beforeclosedialog" v-model="dialogVisible" width="25%" :title="dialogtype == 0 ? '添加' : '修改'">
		<!-- 商品种类 -->
		<el-form ref="formRef" :model="GoodsCategoryform" label-width="90px" v-if="formfalg == 'SET_GoodsCategory'" :rules="rules">
			<el-form-item label="种类名称:" prop="GoodsCategory_name">
				<el-input v-model="GoodsCategoryform.GoodsCategory_name"></el-input>
			</el-form-item>
			<el-form-item label="重量单位:" prop="GoodsCategory_weightunit">
				<el-select v-model="GoodsCategoryform.GoodsCategory_weightunit" placeholder="请选择">
					<el-option key="1" label="g" value="1" />
					<el-option key="2" label="ct" value="2" />
				</el-select>
			</el-form-item>
			<!-- <el-form-item label="计重:" prop="GoodsCategory_weight">
        <el-switch :active-value="1" :inactive-value="0" v-model="GoodsCategoryform.GoodsCategory_weight"></el-switch>
      </el-form-item>
      <el-form-item label="计件:" prop="GoodsCategory_pieces">
        <el-switch :active-value="1" :inactive-value="0" v-model="GoodsCategoryform.GoodsCategory_pieces"></el-switch>
      </el-form-item> -->
		</el-form>
		<!-- 商品名称 -->
		<el-form ref="formRef" :model="GoodsNameform" label-width="100px" v-if="formfalg == 'SET_GoodsName'" :rules="rules">
			<el-form-item label="商品名称:" prop="GoodsName_name">
				<el-input v-model="GoodsNameform.GoodsName_name"></el-input>
			</el-form-item>
		</el-form>
		<!-- 品牌-->

		<el-form ref="formRef" :model="GoodsBrandform" label-width="100px" v-if="formfalg == 'SET_GoodsBrand'" :rules="rules">
			<el-form-item label="品牌名称:" prop="GoodsBrand_name">
				<el-input v-model="GoodsBrandform.GoodsBrand_name"></el-input>
			</el-form-item>
			<el-form-item label="前缀:" prop="GoodsBrand_prefix">
				<el-input v-model="GoodsBrandform.GoodsBrand_prefix"></el-input>
			</el-form-item>
			<el-form-item label="备注:" prop="GoodsBrand_remark">
				<el-input type="textarea" v-model="GoodsBrandform.GoodsBrand_remark"></el-input>
			</el-form-item>
		</el-form>

		<!-- 成色 -->

		<el-form ref="formRef" :model="GoodsGradeform" label-width="100px" v-if="formfalg == 'SET_GoodsGrade'" :rules="rules">
			<el-form-item label="成色名称:" prop="GoodsGrade_name">
				<el-input v-model="GoodsGradeform.GoodsGrade_name"></el-input>
			</el-form-item>
			<el-form-item label="备注:" prop="GoodsGrade_remark">
				<el-input type="textarea" v-model="GoodsGradeform.GoodsGrade_remark"></el-input>
			</el-form-item>
		</el-form>

		<!-- 系列 -->

		<el-form ref="formRef" :model="GoodsSeriesform" label-width="100px" v-if="formfalg == 'SET_GoodsSeries'" :rules="rules">
			<el-form-item label="系列名称:" prop="GoodsSeries_name">
				<el-input v-model="GoodsSeriesform.GoodsSeries_name"></el-input>
			</el-form-item>
			<el-form-item label="备注:" prop="GoodsSeries_remark">
				<el-input type="textarea" v-model="GoodsSeriesform.GoodsSeries_remark"></el-input>
			</el-form-item>
		</el-form>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="cancel(formRef)">取消</el-button>
				<el-button type="primary" @click="dianlogclick(formfalg, formRef)">确认</el-button>
			</span>
		</template>
	</el-dialog>
	<!-- 列选择的弹出框 -->
</template>

<style lang="less" scoped>
//左侧表格的样式
/deep/ .left_table {
	height: calc(100vh-261px);
}

//左侧表格下的每一行样式
/deep/ .left_table .el-table__row {
	cursor: pointer;
}

/deep/ .left_table .el-table__row > td:last-child::after {
	content: url(../../assets/arrow-right.png);

	line-height: 1;
	position: absolute;
	right: 10px;
	top: 50%;
	margin-top: -7px;
}

.el-card_body {
	background-color: white;
	padding: 15px;
}

//右侧表头右上角图标
.ele-tool {
	margin: 5px 0 5px auto;
}

.ele-tool .el-button--small {
	padding: 7px 7px;
	font-size: 15px;
	background-color: #f6f8f9;
}

.ele-table-tool {
	display: inline-flex;
	flex-wrap: wrap;
	width: 100%;
}

//分页
.ele-pagination {
	margin-top: 15px;
	display: flex;
	justify-content: center;
}

/deep/ .operate {
	color: red;
}
</style>
